 //
//  EFBChartsViewController.m
//  muefb
//
//  Created by 蒋 尚秀 on 12-5-2.
//  Copyright (c) 2012年 ADCC. All rights reserved.
//

#import "EFBChartsViewController.h"
#import <SKInnerShadowLayer.h>
#import <AEIdentityManager.h>
#import <EFBContext.h>
#import "EFBNAIP.h"
#import "FMDatabase.h"
#import "NSDate+dateWithString.h"
#import "EFBFavoriteViewController.h"
#import "EFBChartNavigationView.h"
#import "ChartFileHelper.h"
#import "TCAirportModel.h"
#import "TCAirportViewController.h"
#import "TCChartListViewController.h"
#import "NIFLog.h"
#import "EFBChartsVersionViewController.h"
#import "FavoriteList.h"
#import "EFBAviationMapDB.h"
#import "EFBCompanyChartDB.h"
#import "EFBChartTopView.h"
#import "EFBDigestViewController.h"
#import "TCWarningView.h"

#define componentDbName        @"tc.db3"
#define componentDataName      @"data"

#define mainTabbarHeight    0.0f
#define topViewHeight       69.0f
#define favoriteViewHeight    40.0f
#define favoriteViewHeight1    41.0f

#define CGRectForModalPresentationFormSheet   CGRectMake(0,0,600,680)
#define MARKCONTROLVIEW_X 55
#define MARKCONTROLVIEW_Y 350
#define MARKCONTROLVIEW_WIDTH 50
#define MARKCONTROLVIEW_HEIGHT 100

#define JIAOHEDAN    @"校核单"
#define XIUDINGDAN   @"修订单"


@interface EFBChartsViewController() <EFBChartNavigationViewDelegate,EFBFavoriteViewControllerDelegate,UIPopoverControllerDelegate,ReaderViewControllerDelegate,MarkControlViewDelegate,EFBChartsVersionDelegate,EFBDigestViewControllerDelegate,EFBGestureViewDelegate>/*,UIGestureRecognizerDelegate*/

@property (nonatomic, retain) UIButton* versionButton;

@property (nonatomic, retain) NSMutableArray *typesArray;
@property (nonatomic, retain) NSMutableArray* chartsVersionArray;
@property (nonatomic, retain) NSMutableArray* isExpired;

@property (nonatomic, copy) NSString *selectedVersionID;
@property (nonatomic, copy) NSString *historyNum;
@property (nonatomic, copy) NSString* airPDFPath;

@property (nonatomic, copy) NSString *firstChartFileID;
@property (nonatomic, copy) NSString *secondChartFileID;
@property (nonatomic, copy) NSString *currentChartFileID;
@property (nonatomic, copy) NSString *manualPath;
@property (nonatomic, copy) NSString *flightlNum;


@property (nonatomic, retain) NSIndexPath *selectedPath;
@property (nonatomic, retain) UIImageView* notifyImage;

@property (retain, nonatomic) UIPopoverController *airportPopover;
@property (retain, nonatomic) UIPopoverController *favoritePopover;

@property (retain, nonatomic) EFBDigestViewController *digestViewController;
@property (retain, nonatomic) UIPopoverController *digestPopover;
@property (retain, nonatomic) UIButton *digestButton;

@property (retain, nonatomic) TCAirportViewController *airportViewController;
@property (retain, nonatomic) TCChartListViewController *chartListViewContoller;

@property (retain, nonatomic) EFBFavoriteViewController *favoriteView;
@property (retain, nonatomic) EFBChartNavigationView *chartNavgationView;

@property (retain, nonatomic) FavoriteList *favoriteList;

@property (retain, nonatomic) EFBChartTopView *topView;
@property (retain, nonatomic) TCWarningView *warnView;
@property (nonatomic, retain) UIView* notifyView;
@property (nonatomic, retain) UILabel* notifyTime;
@property (nonatomic, retain) UIButton* closeNotifyViewButton;

@end


@implementation EFBChartsViewController
@synthesize versionButton = _versionButton;
@synthesize chartsVersionArray = _chartsVersionArray;
@synthesize isExpired = _isExpired;
@synthesize selectedVersionID;
@synthesize reader;

- (void)dealloc
{
    [selectedVersionID release];
    [_historyNum release];
    [_airPDFPath release];
    [_firstChartFileID release];
    [_secondChartFileID release];
    [_currentChartFileID release];
    [_manualPath release];
    [_flightlNum release];
    [_typesArray release];
    [_airportPopover release];
    [_favoritePopover release];
    [_digestViewController release];
    [_digestPopover release];
    [_airportViewController release];
    [_chartListViewContoller release];
    [_favoriteView release];
    [_chartNavgationView release];
    [_favoriteList release];
    [_topView release];
    [_chartDictionary release];
    [_markControlView release];
    [_tapView release];
    [_notifyImage release];
//    [_versionButton release];
    [_isExpired release];
    [_chartsVersionArray release];
    [reader release];
    [_airPDFPath release];
    [_selectedPath release];
    [_pdfView release];
    [_notifyTime release];
    [_notifyView release];
    [_warnView release];
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(saveReaderViewPlistBefroeRelease) name:@"saveReaderViewPlistBefroeRelease" object:nil];
        [center addObserver:self selector:@selector(writeChartRotationBeforeRelease) name:@"writeChartRotationBeforeRelease" object:nil];
        
        [center addObserver:self selector:@selector(nightmodeChanged:) name:kScreenNightMode object:nil];
        
        [center addObserver:self selector:@selector(closeCharts:) name:@"closeCharts" object:nil];
        [center addObserver:self selector:@selector(chartsDeleteReload) name:@"chartsDeleteReload" object:nil];
        [center addObserver:self selector:@selector(loginNotification) name:@"kLoginNotification" object:nil];

        [center addObserver:self selector:@selector(rotationTheChartView) name:kConextPDFRotation object:nil];
        [center addObserver:self selector:@selector(chartMark:) name:kContextPDFMark object:nil];
        [center addObserver:self selector:@selector(switchVersion) name:kConextPDFVersion object:nil];


        [center addObserver:self selector:@selector(selectedAirportOfChartsChanged:) name:@"selectedAirportOfChartsChanged" object:nil];
        [center addObserver:self selector:@selector(openPDF:) name:@"openPDF" object:nil];
        [center addObserver:self selector:@selector(reloadCharts:) name:@"reloadCharts" object:nil];
        [center addObserver:self selector:@selector(pdfTapped:) name:@"pdfTapped" object:nil];
        
        [center addObserver:self selector:@selector(changeTheVersionChart:) name:@"changeVersionChartByblueT" object:nil];

    }
    return self;
}

- (id)init
{
    self = [super init];
    if (self)
    {
        _historyNum = nil;
        _chartsVersionArray = [[NSMutableArray alloc]init];
        _isExpired = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.topView=[[[EFBChartTopView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 69.0f)] autorelease];
    self.topView.titleLabel.text = @"航图";
    [self.view addSubview:self.topView];
    
    _versionButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_versionButton setBackgroundImage:[UIImage imageNamed:@"effective"] forState:UIControlStateNormal];
    [_versionButton setFrame:CGRectMake(self.view.frame.size.width-121, 25, 121, 34)];
    [_versionButton addTarget:self action:@selector(switchVersion) forControlEvents:UIControlEventTouchUpInside];
    _versionButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
    [_versionButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_versionButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
    [self.topView addSubview:_versionButton];
    
    self.digestButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_digestButton setTitle:@"校验单" forState:UIControlStateNormal];
    [_digestButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_digestButton setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];
    [_digestButton setFrame:CGRectMake(70, 13, 60, 61)];
    [_digestButton addTarget:self action:@selector(showDigestPopover:) forControlEvents:UIControlEventTouchUpInside];
    _digestButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
    [_topView addSubview:_digestButton];
    _digestButton.enabled = NO;
    
    [self createViewInterfaceElement];
    
    [self createViewPopover];
    
    [self addNotifyViewForUpdateChartsVersion];
    
    [self creatMarkControlView];
    
    [self tapViewTest];
    
    if ([[[ChartContext instance] objectForKey:kConextDeviceIsForeign] isEqualToString:@"1"])
    {
        [self showEnglishModeWarningView];
    }
    else
    {
        [self reloadCharts:nil];
    }
}

- (void)tapViewTest
{
    self.tapView = [[[EFBGestureView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height -30)] autorelease];
    self.tapView.delegate = self;
    self.tapView.backgroundColor = [UIColor clearColor];
    self.tapView.alpha = 0.5f;
    self.tapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview: self.tapView];
    self.tapView.hidden = YES;
//    UISwipeGestureRecognizer *leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipes:)];
//    leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
//    leftSwipeGestureRecognizer.numberOfTouchesRequired = 1;
//    leftSwipeGestureRecognizer.delegate = self;
//    leftSwipeGestureRecognizer.cancelsTouchesInView = NO;
//    [self.view addGestureRecognizer:leftSwipeGestureRecognizer];
//
//    UISwipeGestureRecognizer *rightSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipes:)];
//    rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
//    rightSwipeGestureRecognizer.numberOfTouchesRequired = 1;
//    rightSwipeGestureRecognizer.delegate = self;
//    [self.view addGestureRecognizer:rightSwipeGestureRecognizer];
}
 /*
- (void)handleSwipes:(UISwipeGestureRecognizer *)sender
{
    if (sender.direction == UISwipeGestureRecognizerDirectionLeft) {
        [self.favoriteView rightButtonTap];
    }
    
    if (sender.direction == UISwipeGestureRecognizerDirectionRight) {
        [self.favoriteView leftButtonTap];
    }
}
*/
- (void)createViewInterfaceElement
{
    self.notifyImage = [[[UIImageView alloc] initWithFrame:CGRectMake((CGRectGetWidth(self.view.frame)-200)/2, (CGRectGetHeight(self.view.frame)-200)/2, 200, 200)] autorelease];
    self.notifyImage.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleRightMargin;
    self.notifyImage.alpha = 0.7f;
    [self.view addSubview:self.notifyImage];
    
    self.warnView=[[[TCWarningView alloc] initWithFrame:self.view.frame withTitle:@"This function is restricted in English mode."] autorelease];
    [self.view addSubview:self.warnView];
    
    NSArray *titlesArray = @[ @"黄页",@"REF",@"STR",@"APP",@"TXI",@"SID",@"CO",@"细则"];//,@"AR"
    CGRect rect;
    if (UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
        rect = CGRectMake(0, 30, 69, self.view.frame.size.height-200);
    }else{
        rect = CGRectMake(0, 30, 69, self.view.frame.size.height-200);
    }
    _chartNavgationView = [[EFBChartNavigationView alloc] initWithFrame:rect typeArray:titlesArray];
    _chartNavgationView.delegate = self;
    _chartNavgationView.userInteractionEnabled = YES;
    [self.view addSubview:_chartNavgationView];
    
    _chartListViewContoller = [[TCChartListViewController alloc] init];
    CGRect rect1 = CGRectMake(-232, 99, 300, CGRectGetHeight(_chartNavgationView.frame));
    _chartListViewContoller.view.frame = rect1;
    [self.view addSubview:_chartListViewContoller.view];
    _chartListViewContoller.view.layer.masksToBounds = YES;
    _chartListViewContoller.view.layer.cornerRadius = 8.0;
    _chartListViewContoller.view.layer.borderWidth = 1.0;
    _chartListViewContoller.view.hidden = YES;
    [self.view bringSubviewToFront:_chartNavgationView];
    
    self.favoriteView = [[[EFBFavoriteViewController alloc] init] autorelease];
    self.favoriteView.view.frame = CGRectMake(0, CGRectGetHeight(self.view.frame)-favoriteViewHeight, CGRectGetWidth(self.view.frame), favoriteViewHeight);
    self.favoriteView.view.autoresizingMask = UIViewAutoresizingFlexibleTopMargin| UIViewAutoresizingFlexibleWidth;
    self.favoriteView.delegate = self;
    [self.view addSubview:self.favoriteView.view];
}

- (void)createViewPopover
{
    _airportViewController = [[TCAirportViewController alloc] init];
	_airportPopover = [[UIPopoverController alloc] initWithContentViewController:_airportViewController];
	[_airportPopover setPopoverContentSize:CGSizeMake(320, 600) animated:NO];
	[_airportPopover setBackgroundColor:[UIColor colorWithRed:59/255.0 green:70/255.0 blue:85/255.0 alpha:1.0]];
    
    _favoriteList = [[FavoriteList alloc] init];
    _favoritePopover = [[UIPopoverController alloc] initWithContentViewController:_favoriteList];
	[_favoritePopover setPopoverContentSize:CGSizeMake(320, 400) animated:NO];
	[_favoritePopover setBackgroundColor:[UIColor colorWithRed:59/255.0 green:70/255.0 blue:85/255.0 alpha:1.0]];
	_favoritePopover.popoverLayoutMargins = UIEdgeInsetsMake(00, 0, 100, 0);
    
    self.digestViewController = [[[EFBDigestViewController alloc] init] autorelease];
    self.digestViewController.delegate = self;
    self.digestPopover = [[[UIPopoverController alloc] initWithContentViewController:_digestViewController] autorelease];
    if ([UIPopoverController instancesRespondToSelector:@selector(backgroundColor)]) {
        _digestPopover.backgroundColor=[UIColor colorWithRed:59/255.0 green:70/255.0 blue:85/255.0 alpha:1.0];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    if ( ((self.historyNum != nil && ![self.historyNum isEqualToString:@""]) || (self.flightlNum != nil && ![self.flightlNum isEqualToString:@""])) && ![self.historyNum isEqualToString:self.flightlNum]) {
        
        [self closeChart];
        
    }
}


- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    self.historyNum = self.flightlNum;

}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.versionButton=nil;
    self.isExpired = nil;
    self.chartsVersionArray = nil;
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return YES;
}

- (void)viewWillLayoutSubviews
{
    //    [EFBReusedLibraies changeBackGroundPic:self.view];
    //    [self doRotateActionChart];
    CGRect rect;
    if (UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
        rect = CGRectMake(0, 79, 69, self.view.frame.size.height-120);
    }else{
        rect = CGRectMake(0, 99, 69, self.view.frame.size.height-200);
    }
    _chartNavgationView.frame = rect;
    
    CGRect rect1 = _chartListViewContoller.view.frame;
    rect1.origin.y = _chartNavgationView.frame.origin.y;
    rect1.size.height = CGRectGetHeight(_chartNavgationView.frame);
    _chartListViewContoller.view.frame = rect1;
    
    int popover_x = _chartNavgationView.frame.origin.y;
    _airportPopover.popoverLayoutMargins = UIEdgeInsetsMake(popover_x, 0, 0, 0);

    [_chartNavgationView reloadViews];
    
    if (self.pdfView) {
        self.notifyImage.center = self.pdfView.center;
    }else if (self.reader.view)
    {
        self.notifyImage.center = self.reader.view.center;
    }else{
        self.notifyImage.center = self.view.center;
    }
}

#pragma mark - NSNotification
- (void)pdfTapped:(NSNotification*)no
{
    if (!_chartListViewContoller.view.hidden) {
        return;
    }
    BOOL isHidden = [no.object boolValue];

    [[ChartContext instance] setValue:[NSString stringWithFormat:@"%hhd",isHidden] forKey:kContextFullScreen];
    
    int xy = isHidden ? 0 : 69;
    int height = isHidden ? favoriteViewHeight1 : 110;
    
    _topView.hidden =isHidden;
    _chartNavgationView.hidden = isHidden;
    _pdfView.frame=CGRectMake(xy, xy, self.view.frame.size.width-xy, self.view.frame.size.height-height);
}

- (void)selectedAirportOfChartsChanged:(NSNotification *)notification
{
	if (_pdfView) {
		[_pdfView removeFromSuperview];
		self.pdfView = nil;
	}
		
	NSString *icao = notification.object;
	_typesArray = (NSMutableArray *)[TCAirportModel getTypes:icao];

    [self getCODataWithCode4:icao];
//    [self getARDataWithCode4:icao];
    
    self.topView.titleLabel.text = icao;
    
    [_chartNavgationView setAirportLableText:icao];
    
    [_chartNavgationView updateMark:_typesArray];
    
    [self checkCOData:icao];
    
    [self.favoriteView displayPageControl:icao];
    
    NSArray *titlesArray = @[ @"黄页",@"REF",@"STR",@"APP",@"TXI",@"SID",@"CO",@"细则"];//,@"AR"
	NSDictionary *dic = [[TCAirportModel getFavorateDic] objectForKey:icao];
    BOOL isTure = YES;
    for (NSString *string in titlesArray) {
        if (isTure) {
            for (NSDictionary *dic in _typesArray)
            {
                if ([[dic objectForKey:@"typeName"] isEqualToString:string])
                {
                    isTure = NO;
                    [[NSUserDefaults standardUserDefaults] setObject:string forKey:@"chartChildOpened"];
                    [[NSUserDefaults standardUserDefaults] setObject:string forKey:@"chartChildSelected"];
                }
            }
        }
        NSArray *array = [dic objectForKey:string];
        if ([array count] != 0) {
            
            [TCAirportModel setTypeName:string];
            [_chartNavgationView moveMarkForType:string];
            
            //打开对应文件
            [[NSUserDefaults standardUserDefaults] setObject:string forKey:@"chartChildSelected"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"openPDF" object:[array firstObject]];
            
            [TCAirportModel setSelectedDic:[array firstObject]];
            break;
        }
    }
    if (_airportPopover.isPopoverVisible) {
        [_airportPopover dismissPopoverAnimated:YES];
    }
    if (_favoritePopover.isPopoverVisible) {
        [_favoritePopover dismissPopoverAnimated:YES];
    }
}

- (void)checkCOData:(NSString *)icao
{
    //检查CO数据
    NSMutableArray *array = [NSMutableArray arrayWithArray:[[[TCAirportModel getFavorateDic] objectForKey:icao] objectForKey:@"CO"]];
    NSMutableArray *tmpArr = [NSMutableArray array];
    if ([_typesArray count] == 6) {
        NSArray *coData = [[_typesArray lastObject] objectForKey:@"subTypesArray"];
        for (int i = 0; i < [coData count]; i ++) {
            NSArray *array1 = [[coData objectAtIndex:i] objectForKey:@"chartsArray"];
            [tmpArr addObjectsFromArray:array1];
        }
    }
    for (NSDictionary *dic in array) {
        if ([tmpArr count] > 0) {
            int count = 0;
            for (NSDictionary *dict in tmpArr) {
                if (dic[@"uuid"] != nil && [dict[@"uuid"] isEqualToString:dic[@"uuid"]]) {
                    if (![dic isEqual:dict]) {
                        [TCAirportModel changedFavoriteDic:dic key:@"CO" status:@"NO"];
                        [TCAirportModel changedFavoriteDic:dict key:@"CO" status:@"YES"];
                    }
                    break;
                }
                ++ count;
                if (count == [tmpArr count]) {
                    [TCAirportModel changedFavoriteDic:dic key:@"CO" status:@"NO"];
                }
            }
        }
        else {
            [TCAirportModel changedFavoriteDic:dic key:@"CO" status:@"NO"];
        }
    }
}

- (void)openPDF:(NSNotification *)notification
{
	if (notification.object)
	{
		_chartDictionary = (NSMutableDictionary*)notification.object;
	}
	else
	{
        if (!_pdfView) {
            return;
        }
		if (![[_chartDictionary objectForKey:@"isChart"]isEqualToString:@"YES"]) {
			return;
		}
		
		NSString *angle = [[TCAirportModel getRotateDic] objectForKey:[_chartDictionary objectForKey:@"file_name"]];
		if (angle) {
			int angleInt = ([angle intValue] + 90)%360;
			angle = [NSString stringWithFormat:@"%d",angleInt];
		}
		else
		{
			angle = [NSString stringWithFormat:@"%d",90];
		}
		[TCAirportModel setRotateDic:[_chartDictionary objectForKey:@"file_name"] value:angle];
	}
    
	if (_pdfView) {
        [_pdfView clearReaderBeforeRelease];
		[_pdfView removeFromSuperview];
        _pdfView = nil;
	}
    
    if (reader) {
        [self saveReaderViewPlistBefroeRelease];
        [reader.view removeFromSuperview];
        reader=nil;
    }
    
//    if (_favoriteView.view.hidden) {
//        _favoriteView.view.hidden = NO;
//    }
    int origin_x = 69;
    int origin_y = 69;
    if (_chartListViewContoller.view.frame.origin.x > 0) {
        origin_x = 376;
    }
    if (_topView.hidden) {
        origin_x = 0;
        origin_y = 0;
    }
    self.pdfView = [[[TCpdfView alloc] initWithFrame:CGRectMake(origin_x, origin_y, self.view.frame.size.width-origin_x, self.view.frame.size.height-favoriteViewHeight1-origin_y)] autorelease];
    _pdfView.isFull = [[[ChartContext instance] objectForKey:kContextFullScreen] boolValue];
    _pdfView.chartID=self.currentChartFileID;
//    [_pdfView setBackgroundColor:[UIColor clearColor]];
	_pdfView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	[self.view addSubview:_pdfView];
	[_pdfView showPDFWithPath:_chartDictionary];
    
    [self.view bringSubviewToFront:self.tapView];
    [self.view bringSubviewToFront:self.topView];
    [self.view bringSubviewToFront:self.chartListViewContoller.view];
    [self.view bringSubviewToFront:self.chartNavgationView];

    [self.view bringSubviewToFront:self.notifyImage];
        
    NSString *airPort = [TCAirportModel getAirportICAO];
    NSString *type = [TCAirportModel getType];
    
    self.topView.titleLabel.text = [_chartDictionary objectForKey:@"name"];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:type forKey:@"chartChildOpened"];
    
	//收藏标示选中判断
	NSArray *array = [[[TCAirportModel getFavorateDic] objectForKey:airPort] objectForKey:type];
    if ([array containsObject:_chartDictionary]) {
        int index = [array indexOfObject:_chartDictionary];
        [self.favoriteView reloadFavoriteViewWithType:type index:index];
    }
    else {
        if (![type isEqualToString:@"CO"]) {
            NSArray *tmp = [[[TCAirportModel getFavorateDic] objectForKey:airPort] allValues];
            int m =0;
            for (int i = 0; i < [tmp count]; i ++) {
                NSArray *array = [tmp objectAtIndex:i];
                if ([array containsObject:_chartDictionary]) {
                    break;
                }
                m ++;
                if (m == [tmp count]) {
                    [self.favoriteView reloadFavoriteViewWithType:@"" index:-1];
                }
            }
        }
        else
        {
            for (NSDictionary *dic in array) {
                if ((dic[@"uuid"] != nil && [dic[@"uuid"] isEqualToString:_chartDictionary[@"uuid"]])) {
                    [TCAirportModel setFavorateDic:dic value:nil];
                    [TCAirportModel setFavorateDic:_chartDictionary value:@"YES"];
                    int index = [array indexOfObject:_chartDictionary];
                    [self.favoriteView reloadFavoriteViewWithType:type index:index];
                    break;
                }
                [self.favoriteView reloadFavoriteViewWithType:@"" index:-1];
            }
        }
    }
}

#pragma mark - left navigation delegate
- (void)chartAirportButtonClicked:(UIButton *)sender
{
    [self airportButtonTapped:sender];
}

- (IBAction)airportButtonTapped:(id)sender
{
    UIButton *button = (UIButton *)sender;
	if ([_airportPopover isPopoverVisible]) {
		[_airportPopover dismissPopoverAnimated:YES];
		return;
	}
    if (!_chartListViewContoller.view.hidden) {
        [self animateChartListView:NO];
    }
    
    
    [_airportPopover presentPopoverFromRect:button.frame inView:_chartNavgationView permittedArrowDirections:UIPopoverArrowDirectionLeft animated:NO];
}

- (void)favoriteButtonClicked:(UIButton *)sender
{
    UIButton *button = (UIButton *)sender;
	if ([_airportPopover isPopoverVisible]) {
		[_airportPopover dismissPopoverAnimated:YES];
	}
    if (!_chartListViewContoller.view.hidden) {
        [self animateChartListView:NO];
    }
    
    
    [_favoritePopover presentPopoverFromRect:button.frame inView:_chartNavgationView permittedArrowDirections:UIPopoverArrowDirectionLeft animated:NO];
}

- (void)chartTypeButtonClicked:(UIButton *)sender
{
    [self getCODataWithCode4:[TCAirportModel getAirportICAO]];
    [self checkCOData:[TCAirportModel getAirportICAO]];

    [self buttonsTapped:sender];
}

- (IBAction)buttonsTapped:(id)sender
{
	[_airportPopover dismissPopoverAnimated:NO];
	

	if ([(UIButton *)sender isSelected])
	{
        if (_chartListViewContoller.view.frame.origin.x > 0) {
            [self animateChartListView:NO];
        }else{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"selectedTypeChanged" object:((UIButton*)sender).titleLabel.text];
            [self animateChartListView:YES];
        }
        return;
	}
    [[NSNotificationCenter defaultCenter] postNotificationName:@"selectedTypeChanged" object:((UIButton*)sender).titleLabel.text];

	[self openTheSelectedPDF:(UIButton*)sender];
}

- (void)openTheSelectedPDF:(UIButton *)button
{
    @autoreleasepool {
        
        NSString *key = [[TCAirportModel getAirportICAO] stringByAppendingString:button.titleLabel.text];
        NSDictionary *chartDic = [[TCAirportModel getSelectedDic] objectForKey:key];
        NSArray *subTypesArray = [TCAirportModel getSubTypes:button.titleLabel.text];
        BOOL isContains = NO;
        for (NSDictionary *dic in subTypesArray) {
            if ([[dic objectForKey:@"chartsArray"] containsObject:chartDic]) {
                isContains = YES;
                break;
            }
        }
        if (!isContains) {
            [[TCAirportModel getSelectedDic] removeObjectForKey:key];
            chartDic = nil;
        }
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:button.titleLabel.text forKey:@"chartChildSelected"];
        
        //	NIF_TRACE(@"selectedDic \n %@",[TCAirportModel getSelectedDic]);
        if (chartDic != nil)
        {
            //        [self animateChartListView:NO];
            NSDictionary *d = [NSDictionary dictionaryWithDictionary:chartDic];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"openPDF" object:d];
        }
        else
        {
            [self animateChartListView:YES];
        }
    }
}

- (void)animateChartListView:(BOOL)isHidden
{
    int x = isHidden ? 75 : -232;
    int x1 = isHidden ? 376 : 69;
    
    [[NSUserDefaults standardUserDefaults] setObject:@"NO" forKey:@"kChartViewControllerHidden"];
    if (isHidden) {
        self.tapView.hidden = NO;
        [self.view bringSubviewToFront:self.tapView];
        [self.view bringSubviewToFront:_chartListViewContoller.view];
        [self.view bringSubviewToFront:_chartNavgationView];
        [self.view bringSubviewToFront:self.topView];
        [[NSUserDefaults standardUserDefaults] setObject:@"YES" forKey:@"kChartViewControllerHidden"];

    }
    
    [UIView animateKeyframesWithDuration:0.3 delay:0 options:UIViewKeyframeAnimationOptionBeginFromCurrentState animations:^{
        
        _chartListViewContoller.view.hidden = NO;
        
        CGPoint point1 = self.view.center;
        if (self.pdfView) {
            self.pdfView.frame=CGRectMake(x1, 69, self.view.frame.size.width-x1, self.view.frame.size.height-favoriteViewHeight1-69);
            point1 = self.pdfView.center;
        }
        
        if (reader) {
            self.reader.view.frame=CGRectMake(x1, 69, self.view.frame.size.width-x1, self.view.frame.size.height-favoriteViewHeight1-69);
            point1 = self.reader.view.center;
        }
        
        CGRect rect = _chartListViewContoller.view.frame;
        rect.origin.x = x;
        _chartListViewContoller.view.frame = rect;
        
        CGPoint point = isHidden ? point1 : self.view.center;

        self.notifyImage.center = point;

    } completion:^(BOOL finished) {
        if (!isHidden && finished) {
            _chartListViewContoller.view.hidden = YES;
            self.tapView.hidden = YES;
            
            NSString *type = [TCAirportModel getType];
            NSString *airport = [TCAirportModel getAirportICAO];
            NSString *userDefaultType = [[NSUserDefaults standardUserDefaults] objectForKey:@"chartChildOpened"];
            if (![type isEqualToString:userDefaultType] && userDefaultType.length > 0 && airport.length > 0) {
                [_chartNavgationView moveMarkForType:userDefaultType];
                [[NSUserDefaults standardUserDefaults] setObject:userDefaultType forKey:@"chartChildSelected"];
            }else{
                [_chartNavgationView moveMarkForType:type];
            }
        }
    }];
}

#pragma mark - showEnglishModeWarningView
- (void)showEnglishModeWarningView
{
    [_versionButton setTitleEdgeInsets:UIEdgeInsetsMake(20, 1, 20, 13)];
    [_versionButton setTitle:NSLocalizedString(@"chart-no-data",@"无数据") forState:UIControlStateNormal];
    [_versionButton setBackgroundImage:[UIImage imageNamed:@"effective"] forState:UIControlStateNormal];
    [_versionButton setEnabled:NO];
    
    self.notifyImage.image = [UIImage imageNamed:@""];
    TCWarningView *warnView=[[[TCWarningView alloc] initWithFrame:self.view.frame withTitle:@"This function is restricted in English mode."] autorelease];
    warnView.alpha=0.7f;
    [self.view addSubview:warnView];

}

#pragma mark - 旋转航图
- (void)rotationTheChartView
{
    BOOL isChart = [[_chartDictionary objectForKey:@"isChart"] boolValue];
    if (_pdfView && isChart) {
        [_pdfView.reader makeContentViewRotaion];
        
        NSString *value = [NSString stringWithFormat:@"%d",self.pdfView.reader.char_rotation];
        [TCAirportModel setRotateDic:[_chartDictionary objectForKey:@"file_name"] value:value];
    }
}

#pragma mark - 释放航图对象之前保存航图旋转角度
- (void)writeChartRotationBeforeRelease
{

}

#pragma mark - 日/夜间模式切换
-(void)nightmodeChanged:(NSNotification*)notification
{
    if (reader) {
        if (self.airPDFPath!=nil && ![self.airPDFPath isEqualToString:@""]) {
            NSString * value = [NSString stringWithFormat:@"%@",[notification.userInfo objectForKey:kScreenNightMode]];
            [[PDFContext instance] setValue:value forKey:kPDFContextNightModel];
            [self showPDFWithPath:self.airPDFPath];
            
        }
    }
    else if(_pdfView)
    {
        NSString * value = [NSString stringWithFormat:@"%@",[notification.userInfo objectForKey:kScreenNightMode]];
        [[PDFContext instance] setValue:value forKey:kPDFContextNightModel];
        [_pdfView showPDFWithPath:_chartDictionary];
    }
}

#pragma mark - 标注
- (void)chartMark:(NSNotification *)object
{
    BOOL isSelected = [object.object boolValue];
    if (_pdfView) {
        NSNumber *key = [NSNumber numberWithInteger:_pdfView.reader.currentPage];
        ReaderContentView *contentView = [_pdfView.reader.contentViews objectForKey:key];
        
        if (isSelected)
        {
            [contentView.pdfMarkFunction.delegate getZoomScale];
            contentView.scrollEnabled=NO;
            contentView.pdfMarkFunction.hidden =NO;
            contentView.pdfMarkFunction.userInteractionEnabled=YES;
            contentView.pdfMarkFunction.backgroundColor=[UIColor clearColor];
            [_pdfView bringSubviewToFront:contentView.pdfMarkFunction];
            _pdfView.reader.theScrollView.scrollEnabled = NO;
            _pdfView.reader.mainPagebar.userInteractionEnabled = NO;
            self.markControlView.hidden=NO;
            [self.view bringSubviewToFront:self.markControlView];
            
            _chartNavgationView.userInteractionEnabled = NO;
            _favoriteView.view.userInteractionEnabled = NO;
        }
        else
        {
            contentView.scrollEnabled=YES;
            [contentView.pdfMarkFunction pointPath];
            contentView.pdfMarkFunction.userInteractionEnabled=NO;
            _pdfView.reader.theScrollView.scrollEnabled = YES;
            _pdfView.reader.mainPagebar.userInteractionEnabled = YES;
            self.markControlView.hidden=YES;
            
            _chartNavgationView.userInteractionEnabled = YES;
            _favoriteView.view.userInteractionEnabled = YES;
        }
    }
}

#pragma mark - ReaderViewController Delegate Method
- (void)showPDFWithPath:(NSString *)pdfPath{
    self.airPDFPath = pdfPath;
    
    if (!pdfPath) {
        return;
    }
    
    if (_pdfView) {
        [_pdfView removeFromSuperview];
        _pdfView = nil;
    }

    if (reader) {
        [self saveReaderViewPlistBefroeRelease];
        [reader.view removeFromSuperview];
        reader=nil;
    }
    
//    if (!_favoriteView.view.hidden) {
//        _favoriteView.view.hidden = YES;
//    }
    NSString *version = [[ChartContext instance] objectForKey:CTX_CHART_VERSION];
    NSString *passWord = [EFBNAIP passwordWithFile:[pdfPath lastPathComponent] andVersion:version];
	ReaderDocument *document =[ReaderDocument newWithDocumentFilePath:pdfPath password:passWord];
    self.reader = [[[ReaderViewController alloc] initWithReaderDocument:document] autorelease];
    reader.isChar = NO;
    reader.isPerformance=NO;
    self.reader.view.frame = CGRectMake(69, topViewHeight, self.view.frame.size.width-69, self.view.frame.size.height-topViewHeight-favoriteViewHeight1);
    self.reader.delegate = self;
    [self.view addSubview:reader.view];
    [self.view bringSubviewToFront:self.notifyImage];
    [document release];
}

#pragma mark - 释放PDF对象之前保存PDF文档信息
- (void)saveReaderViewPlistBefroeRelease
{
    if (reader) {
        [reader saveBeforeReleaseOrHiddenReaderView];
    }
}

#pragma mark - ReaderViewController Delegate Method
- (void)thePdfDisplayed{
    
}

- (void)dismissReaderViewController:(ReaderViewController *)viewController{
    return;
}

- (void)contentViewTapGestureRecognizer:(BOOL)isHidden
{
//    [[EFBMethodForReaderViewController shareMethod] tapToHiddenTopAndTabbar1:reader isHidden:isHidden withFrame:self.view.bounds];
//    self.fullScreenMode = isHidden;//!self.fullScreenMode;
}

#pragma mark - 下载完后后更新
- (void)reloadCharts:(NSNotification*)notification
{
    if (![[[ChartContext instance] objectForKey:kDeviceIsForeign] isEqualToString:@"1"]) {
        
        if (self.warnView.alpha != 0.0f) {
            [self.warnView hiddenWarningView];
        }
        if(notification)
        {
            NSString* tag = notification.object;
            if ([tag isEqualToString:@"download complete"]) {
                [self refreshNotifyView];
            }
        }
//        [activity start];
        
        [self loadChartsInfoFromDatabase];
        [self getCurrentChartVersion];
        [self unzipFile];
    }
    else
    {
        if (self.warnView.alpha == 0.0f) {
            self.warnView.titleLabel.text = @"This function is restricted in English mode.";
            [self.warnView showWarningView];
        }
        [self showEnglishModeWarningView];
        _digestButton.enabled = NO;
    }
}

-(void)refreshNotifyView
{
    _notifyTime.text = [self getCurrentDateString];
    [_notifyView setHidden:NO];
}

-(NSString*)getCurrentDateString
{
    NSDateFormatter * dateFormat = [[[NSDateFormatter alloc] init] autorelease];
    dateFormat.dateFormat = @"yyyy-MM-dd HH:mm:ss+0800";
    NSString* dateString = [dateFormat stringFromDate:[NSDate date]];
    return dateString;
}

#pragma mark --[航图版本已更新]提示View
-(void)addNotifyViewForUpdateChartsVersion
{
    self.notifyView = [[[UIView alloc]initWithFrame:CGRectMake((self.view.frame.size.width-380)/2, self.view.frame.size.height-220, 380, 100)] autorelease];
    _notifyView.layer.cornerRadius = 15.0;
    [_notifyView setBackgroundColor:[UIColor blackColor]];
    [_notifyView setAlpha:0.6];
    _notifyView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin |UIViewAutoresizingFlexibleRightMargin;
    //提示内容
    UILabel* notifyContent = [[[UILabel alloc] init] autorelease];
    notifyContent.text = @"航图版本已更新";
    notifyContent.textColor = [UIColor whiteColor];
    notifyContent.backgroundColor = [UIColor clearColor];
    notifyContent.font = [UIFont systemFontOfSize:30.0];
    notifyContent.textAlignment = NSTextAlignmentCenter;
    notifyContent.frame = CGRectMake(50, 20, 280, 40);
    //提示时间
    self.notifyTime = [[[UILabel alloc] init] autorelease];
    _notifyTime.text = [self getCurrentDateString];
    _notifyTime.backgroundColor = [UIColor clearColor];
    _notifyTime.textColor = [UIColor whiteColor];
    _notifyTime.font = [UIFont systemFontOfSize:20.0];
    _notifyTime.textAlignment = NSTextAlignmentCenter;
    _notifyTime.frame = CGRectMake(50, 60, 280, 40);
    [_notifyView addSubview:_notifyTime];
    [_notifyView addSubview:notifyContent];
    
    //关闭提示窗口按钮
    self.closeNotifyViewButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_closeNotifyViewButton setImage:[UIImage imageNamed:@"warning-close"] forState:UIControlStateNormal];
    [_closeNotifyViewButton setFrame:CGRectMake(348, 4, 28, 28)];
    [_closeNotifyViewButton addTarget:self action:@selector(closeNotifyTapped:) forControlEvents:UIControlEventTouchUpInside];
    [_notifyView addSubview:_closeNotifyViewButton];
    
    [self.view addSubview:_notifyView];
    [_notifyView setHidden:YES];
    
}

-(void)closeNotifyTapped:(id)sender
{
    [_notifyView setHidden:YES];
}

#pragma mark - 航图删除更新
- (void)chartsDeleteReload
{
    self.digestButton.enabled = NO;
    [self closeChart];
    [self reloadCharts:nil];
    [_notifyView setHidden:YES];
}

- (void)closeCharts:(NSNotification*)notification
{
    [self closeChart];
}

- (void)closeChart
{
    if (reader) {
        [self saveReaderViewPlistBefroeRelease];
        [reader.view removeFromSuperview];
        [reader release]; reader=nil;
    }
    if (_pdfView) {
		[_pdfView removeFromSuperview];
		self.pdfView = nil;
	}
    if (_airportPopover)
    {
        [_airportPopover dismissPopoverAnimated:YES];
        _airportPopover = nil;
    }
    
    if (_airportViewController)
    {
        [_airportViewController release];
        _airportViewController=nil;
    }
    
    self.airportViewController = [[[TCAirportViewController alloc] init] autorelease];
	_airportPopover = [[UIPopoverController alloc] initWithContentViewController:_airportViewController];
	[_airportPopover setPopoverContentSize:CGSizeMake(320, 600) animated:NO];
	[_airportPopover setBackgroundColor:[UIColor blackColor]];
    _airportPopover.popoverLayoutMargins = UIEdgeInsetsMake(100, 0, 0, 0);

    [_chartNavgationView clearButtonTypeShowInfo];
    [_favoriteView displayPageControl:@""];
    [TCAirportModel removeSelectedDicAndAirportICAO];
    
    self.topView.titleLabel.text = @"航图";
}


#pragma mark - 查看航图版本
-(void)switchVersion
{
    EFBChartsVersionViewController* selectController = [[[EFBChartsVersionViewController alloc] initWithStyle:UITableViewStyleGrouped] autorelease];
    selectController.modalPresentationStyle = UIModalPresentationFormSheet;
    selectController.dataSouceArray = self.chartsVersionArray;
    for (int i = 0; i<self.chartsVersionArray.count; i++)
    {
		if ([[[self.chartsVersionArray objectAtIndex:i] objectForKey:@"revision_id"] isEqualToString:self.selectedVersionID])
        {
			selectController.selectedIndex = i;
		}
	}
    
    [self.isExpired removeAllObjects];
    for (int i=0; i<self.chartsVersionArray.count; i++) {
        NSDate* effectiveTime = [[ self.chartsVersionArray objectAtIndex:i] objectForKey:@"effective_time"];
        NSDate* expireTime = [[ self.chartsVersionArray objectAtIndex:i] objectForKey:@"expire_time"];
        NSDate* effectiveTime0 = [[ self.chartsVersionArray objectAtIndex:0] objectForKey:@"effective_time"];
        if ( (i==1 && [effectiveTime compare:effectiveTime0] == NSOrderedAscending) || (expireTime != nil && [expireTime compare:[NSDate date]] == NSOrderedAscending)) {
            [self.isExpired addObject:[NSNumber numberWithInt:1]];
        }
        else if(effectiveTime != nil && [effectiveTime compare:[NSDate date]] == NSOrderedAscending && (expireTime==nil || (expireTime!=nil && [expireTime compare:[NSDate date]] == NSOrderedDescending)))
        {
            [self.isExpired addObject:[NSNumber numberWithInt:0]];
        }
        else
        {
            [self.isExpired addObject:[NSNumber numberWithInt:-1]];
        }
    }
    selectController.isExpired = self.isExpired;
    selectController.delegate = self;
    
    UINavigationController * nav = [[[UINavigationController alloc] initWithRootViewController:selectController] autorelease];
    nav.modalPresentationStyle = UIModalPresentationFormSheet;
//    if (!_isBlueTooth){
        [self presentViewController:nav animated:YES completion:nil];
//    }
    
    if (!self.chartListViewContoller.view.hidden) {
        [self animateChartListView:NO];
    }
}

#pragma mark - 版本切换
- (void)versionChanged:(int)selectedIndex
{
//    [self switchVersion];
    
    [self getCurrentChartVersion];
    
    [self closeChart];
    _digestButton.enabled = NO;
    _selectIndex=selectedIndex;

    if (selectedIndex == 0) {
        self.currentChartFileID = self.firstChartFileID;
    }
    else
    {
        self.currentChartFileID = self.secondChartFileID;
    }
    
    NSDictionary *dicChart=[_chartsVersionArray objectAtIndex:selectedIndex];
    if (dicChart)
    {
        NSString *uuidStr=[dicChart objectForKey:@"file_id"];
        [[ChartContext instance]setValue:uuidStr forKey:CHART_GETID];
    }
    
    [self getCurrentChartVersion];
    
    self.selectedVersionID = [[_chartsVersionArray objectAtIndex:selectedIndex] objectForKey:@"revision_id"];
    if ([[self.isExpired objectAtIndex:selectedIndex] isEqualToValue:[NSNumber numberWithInt:1]]) {
        [_versionButton setBackgroundImage:[UIImage imageNamed:@"expired"] forState:UIControlStateNormal];
        self.notifyImage.image = [UIImage imageNamed:@"expired_mark"];
        [_pdfView removeFromSuperview];
    }
    else if([[self.isExpired objectAtIndex:selectedIndex] isEqualToValue:[NSNumber numberWithInt:0]])
    {
        [_versionButton setBackgroundImage:[UIImage imageNamed:@"effective"] forState:UIControlStateNormal];
        self.notifyImage.image = [UIImage imageNamed:@""];
        [_pdfView removeFromSuperview];
    }
    else
    {
        [_versionButton setBackgroundImage:[UIImage imageNamed:@"notEffective"] forState:UIControlStateNormal];
        self.notifyImage.image = [UIImage imageNamed:@"notEffective_mark"];
        [_pdfView removeFromSuperview];
    }
    [_versionButton setTitleEdgeInsets:UIEdgeInsetsMake(20, 1, 20, 13)];
    [self.versionButton setTitle:[self dateToString:[[_chartsVersionArray objectAtIndex:selectedIndex] objectForKey:@"effective_time"]] forState:UIControlStateNormal];
    
    self.digestViewController.dataSourceArray = [NSArray arrayWithArray:[self getDigestButtonEnable]];

    NSString* selectedIndexStr = [NSString stringWithFormat:@"%d",selectedIndex];
    [self performSelectorInBackground:@selector(versionChangedWithDate:) withObject:selectedIndexStr];
}

#pragma mark --数据操作
- (void)unzipFile
{
    if (_chartsVersionArray.count!=0)
    {
        NSString *dbPath= [ChartFileHelper pathForChartsDB:self.currentChartFileID];
        [TCAirportModel loadAirportFromDB:dbPath uuid:self.currentChartFileID];
    }
}

- (void)getCurrentChartVersion
{
    FMDatabase* db = [FMDatabase databaseWithPath:[self getCurrentChartsFolderPath:componentDbName]];
    
    NSString* sql = [NSString stringWithFormat:@"SELECT * FROM t_version"];
    bool ret = [db openWithFlags:SQLITE_OPEN_READONLY];
    if (!ret) {
        NIF_TRACE(@"航图数据库打开错误！");
        return;
    }
    FMResultSet*    results = [db executeQuery:sql];
    NSString* chartVersion = nil;
    while( [results next] )
    {
        chartVersion = [results objectForColumnName:@"version"];
    }
    [[ChartContext instance] setValue:chartVersion forKey:CTX_CHART_VERSION];
    
    [db close];
}

- (void)changeButtonState
{
//    [self airportButtonTapped:nil];
}

- (void)versionChangedWithDate:(NSString*)versionIndexStr
{
    int versionIndex = versionIndexStr.intValue;
    NSString* dbPath;
    if (versionIndex) {
        dbPath = self.secondChartFileID ;
    }
    else
    {
        dbPath = self.firstChartFileID;
    }
    
    NSString *chartManagerFilePath = [ChartFileHelper pathForChartsDB:dbPath];
    [TCAirportModel loadAirportFromDB:chartManagerFilePath uuid:dbPath];
    
    [self performSelectorOnMainThread:@selector(changeButtonState) withObject:self waitUntilDone:YES];
}

//此方法用来区分新版与老版航图下面文件取不同路径的问题
- (NSString *)getCurrentChartsFolderPath:(NSString *)componentString
{
    NSString *currentFolderPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Documents/charts/" stringByAppendingPathComponent:self.currentChartFileID]];
    if ([[NSFileManager defaultManager] fileExistsAtPath:[currentFolderPath stringByAppendingPathComponent:@"naip"]]) {
        return [[currentFolderPath stringByAppendingPathComponent:@"naip"] stringByAppendingPathComponent:componentString];
    }
    return [currentFolderPath stringByAppendingPathComponent:componentString];
}

- (NSString *)flightlNum
{
    return [[ChartContext instance] objectForKey:CTX_TASK_FLIGHT_NO];
}

- (CGFloat)sizeWithButton:(UIButton *)button
{
    CGSize buttonSize=CGSizeMake(CGFLOAT_MAX,61);
    UIFont *font = [UIFont boldSystemFontOfSize:[UIFont buttonFontSize]];
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
    
    CGSize requiredSize =[button.titleLabel.text boundingRectWithSize:buttonSize options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
    
    return requiredSize.width;
}

- (NSString*)dateToString:(NSDate*)date
{
    NSDateFormatter * dateFormat = [[[NSDateFormatter alloc] init] autorelease];
    dateFormat.dateFormat = @"yyyy-MM-dd";
    NSString* dateString = [dateFormat stringFromDate:date];
    if(dateString == nil || [dateString isEqualToString:@""])
    {
        dateString = @"长期有效";
    }
    return dateString;
}

- (NSDictionary*)dictionaryFromRevisionRow:(NSDictionary*)dic
{
    return [[[NSDictionary alloc] initWithObjectsAndKeys:[NSDate dateWithString:[dic objectForKey:@"effective_time"]],@"effective_time",[dic objectForKey:@"cycle_name"],@"revision_nver",[dic objectForKey:@"file_id"], @"file_id",[NSDate dateWithString:[dic objectForKey:@"expire_time"]],@"expire_time",[dic objectForKey:@"revision-number"],@"revision_id",nil] autorelease];
}


#pragma mark-- 获取航图有效版本
- (void)getChartVersions
{
    if (_chartsVersionArray)
    {
        [_chartsVersionArray removeAllObjects];
    }
    
    NSMutableDictionary *dicPlist = nil;
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:[ChartFileHelper pathForChartsPlist]])
    {
        dicPlist = [[[NSMutableDictionary alloc] initWithContentsOfFile:[ChartFileHelper pathForChartsPlist]]autorelease];
    }
    NSDictionary* currentDic = nil;
    NSDictionary* otherDic = nil;
    if ([dicPlist count] != 0)
    {
        NSMutableDictionary  *dicVersion1 = [NSMutableDictionary dictionaryWithDictionary:[dicPlist objectForKey:@"1"]];
        NSMutableDictionary *dicVersion2 = [NSMutableDictionary dictionaryWithDictionary:[dicPlist objectForKey:@"2"]];
        
        NSString *effectivedate1 = nil;
        if ([dicVersion1 count] != 0)
        {
            effectivedate1 = [dicVersion1 objectForKey:@"effective_date"];
            if (effectivedate1 != nil&& ![effectivedate1 isEqualToString:@""])
            {
                [dicVersion1 setValue:effectivedate1 forKey:@"effective_time"];
                NSString *expireTime = [self GetTomorrowDay:effectivedate1];
                [dicVersion1 setValue:expireTime forKey:@"expire_time"];
            }
        }
        
        NSString *effectivedate2 = nil;
        if ([dicVersion2 count] != 0)
        {
            effectivedate2 = [dicVersion2 objectForKey:@"effective_date"];
            if (effectivedate2 != nil&& ![effectivedate2 isEqualToString:@""])
            {
                [dicVersion2 setValue:effectivedate2 forKey:@"effective_time"];
                NSString *expireTime = [self GetTomorrowDay:effectivedate2];
                [dicVersion2 setValue:expireTime forKey:@"expire_time"];
            }
        }
        
        
        if (effectivedate1 != nil&&effectivedate2 == nil)
        {
            currentDic = [self dictionaryFromRevisionRow:dicVersion1];
            [_chartsVersionArray addObject:currentDic];
            
        }else if (effectivedate1 == nil&&effectivedate2 != nil)
        {
            currentDic = [self dictionaryFromRevisionRow:dicVersion2];
            [_chartsVersionArray addObject:currentDic];
        }else if (effectivedate1 != nil&&effectivedate2 != nil)
        {
            NSDate* effectiveDate1 = [NSDate dateWithString:[dicVersion1 objectForKey:@"effective_time"]];
            NSDate* effectiveDate2 = [NSDate dateWithString:[dicVersion2 objectForKey:@"effective_time"]];
            
            NSComparisonResult result = [effectiveDate1 compare:effectiveDate2];
            NSDate *nowdate = [NSDate date];
            
            currentDic = [self dictionaryFromRevisionRow:dicVersion1];
            otherDic = [self dictionaryFromRevisionRow:dicVersion2];
            
            if (result == NSOrderedAscending)
            {
                if ([effectiveDate2 compare:nowdate] == NSOrderedAscending)
                {
                    [_chartsVersionArray addObject:otherDic];
                    [_chartsVersionArray addObject:currentDic];
                }else
                {
                    [_chartsVersionArray addObject:currentDic];
                    [_chartsVersionArray addObject:otherDic];
                }
                
            }else
            {
                if ([effectiveDate1 compare:nowdate] == NSOrderedAscending)
                {
                    [_chartsVersionArray addObject:currentDic];
                    [_chartsVersionArray addObject:otherDic];
                }else
                {
                    [_chartsVersionArray addObject:otherDic];
                    [_chartsVersionArray addObject:currentDic];
                }
            }
        }
    }
}

- (NSString *)GetTomorrowDay:(NSString *)aDate
{
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]autorelease];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.sssZZZZZ"];
    NSDate *tempdate = [dateFormatter dateFromString:aDate];
    
    NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:tempdate];
    [components setDay:([components day] + 28)];
    [components setHour:00];
    [components setMinute:00];
    
    NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
    NSString *tempDateString = [dateFormatter stringFromDate:beginningOfWeek];
    return tempDateString;
}

- (void)changeVersionButtonState
{
    if (_chartsVersionArray.count == 0) {
        [_versionButton setTitleEdgeInsets:UIEdgeInsetsMake(20, 1, 20, 13)];
        [_versionButton setTitle:NSLocalizedString(@"chart-no-data",@"无数据") forState:UIControlStateNormal];
        [_versionButton setBackgroundImage:[UIImage imageNamed:@"effective"] forState:UIControlStateNormal];
        [_versionButton setEnabled:NO];
        [self.notifyImage setImage:[UIImage imageNamed:@""]];
        
    }else{
        
        NSDate* expireTime = [[ self.chartsVersionArray objectAtIndex:0] objectForKey:@"expire_time"];
        NSDate* effectiveTime = [[ self.chartsVersionArray objectAtIndex:0] objectForKey:@"effective_time"];
        
        if (expireTime != nil && [expireTime compare:[NSDate date]] == NSOrderedAscending) {
            [_versionButton setBackgroundImage:[UIImage imageNamed:@"expired"] forState:UIControlStateNormal];
            [self.notifyImage setImage:[UIImage imageNamed:@"expired_mark"]];
        }
        else if(effectiveTime != nil && [effectiveTime compare:[NSDate date]] == NSOrderedDescending)
        {
            [_versionButton setBackgroundImage:[UIImage imageNamed:@"notEffective"] forState:UIControlStateNormal];
            [self.notifyImage setImage:[UIImage imageNamed:@"notEffective_mark"]];
        }
        else
        {
            [_versionButton setBackgroundImage:[UIImage imageNamed:@"effective"] forState:UIControlStateNormal];
            self.notifyImage.image = [UIImage imageNamed:@""];
        }
        [_versionButton setEnabled:YES];
        [_versionButton setTitleEdgeInsets:UIEdgeInsetsMake(20, 1, 20, 13)];
        [_versionButton setTitle:[self dateToString:[[_chartsVersionArray objectAtIndex:0] objectForKey:@"effective_time"]] forState:UIControlStateNormal];
        _notifyTime.text = [self getCurrentDateString];
    }
    
}

#pragma mark --加载航图信息
- (int)loadChartsInfoFromDatabase
{
    [self getChartVersions];
    if (_chartsVersionArray.count != 0) {
        NSString *file_id = [[_chartsVersionArray objectAtIndex:0] objectForKey:@"file_id"];
        if (file_id == nil) {
            [[_chartsVersionArray objectAtIndex:0] objectForKey:@"url"];
        }
        self.firstChartFileID = file_id;
        if (_chartsVersionArray.count == 2) {
            NSString *file_id = [[_chartsVersionArray objectAtIndex:1] objectForKey:@"file_id"];
            if (file_id == nil) {
                [[_chartsVersionArray objectAtIndex:0] objectForKey:@"url"];
            }
            self.secondChartFileID = file_id;
        }
    }
    
    if(_chartsVersionArray.count == 0)
    {
        [self performSelectorOnMainThread:@selector(changeVersionButtonState) withObject:self waitUntilDone:YES];
        return 0;
    }
    
    self.selectedVersionID = [[self.chartsVersionArray objectAtIndex:0] objectForKey:@"revision_id"];
    
    self.currentChartFileID = self.firstChartFileID;
    
    [_versionButton setTitleEdgeInsets:UIEdgeInsetsMake(20, 1, 20, 13)];
    [_versionButton setTitle:[self dateToString:[[_chartsVersionArray objectAtIndex:0] objectForKey:@"effective_time"]] forState:UIControlStateNormal];
    
    [self getCurrentChartVersion];
    
    self.digestViewController.dataSourceArray = [NSArray arrayWithArray:[self getDigestButtonEnable]];

    [self performSelectorOnMainThread:@selector(changeVersionButtonState) withObject:self waitUntilDone:YES];
    
    return 1;
}

#pragma mark - EFBFavoriteViewControllerDelegate
- (void)nextOrPreviousChartClickedWithType:(NSString *)type index:(int)index
{
    NSString *airPort = [TCAirportModel getAirportICAO];
    NSString *currentType = [TCAirportModel getType];
    NSArray *array = [[[TCAirportModel getFavorateDic] objectForKey:airPort] objectForKey:type];
    
    NSMutableDictionary *chartDic = [NSMutableDictionary dictionaryWithDictionary:[array objectAtIndex:index]];
    
    //打开对应文件
    [[NSUserDefaults standardUserDefaults] setObject:type forKey:@"chartChildSelected"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"openPDF" object:chartDic];
    
    //更新左侧工具栏
    if (![currentType isEqualToString:type]) {
        [TCAirportModel setTypeName:type];
        [_chartNavgationView moveMarkForType:type];
        [[NSUserDefaults standardUserDefaults] setObject:type forKey:@"chartChildOpened"];
    }
    [TCAirportModel setSelectedDic:chartDic];

    //更新航图列表
    [[NSNotificationCenter defaultCenter] postNotificationName:@"selectedTypeChanged" object:type];
}

#pragma mark - MarkControlViewDelegate
//- (MarkControlView *)creatMarkControlView
//    return self.markControlView;
- (void)creatMarkControlView
{
    self.markControlView=[[[MarkControlView alloc]initWithFrame:CGRectMake(self.view.frame.size.width- MARKCONTROLVIEW_X, self.view.bounds.size.height-MARKCONTROLVIEW_HEIGHT-200, MARKCONTROLVIEW_WIDTH, MARKCONTROLVIEW_HEIGHT)]autorelease];
    self.markControlView.backgroundColor=[UIColor colorWithRed:82/255.0 green:82/255.0 blue:82/255.0 alpha:0.9];
    self.markControlView.autoresizingMask=UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleBottomMargin;
    self.markControlView.delegate=self;
    self.markControlView.hidden=YES;
    [self.view addSubview:self.markControlView];
}

- (void)revocation
{
    NSNumber *key = [NSNumber numberWithInteger:_pdfView.reader.currentPage];
    ReaderContentView *contentView = [_pdfView.reader.contentViews objectForKey:key];
    [contentView.pdfMarkFunction myLineFinallyClear];
}

- (void)remove
{
    NSNumber *key = [NSNumber numberWithInteger:_pdfView.reader.currentPage];
    ReaderContentView *contentView = [_pdfView.reader.contentViews objectForKey:key];
    [contentView.pdfMarkFunction myAllLinesClear];
}

#pragma mark - 获取 CO 和 AR
- (void)getCODataWithCode4:(NSString *)icao
{
    NSMutableArray *theSQLCOInfoArr = [EFBCompanyChartDB getTheCompanyChartsByCode4:icao];
//    NSLog(@"theSQLCOInfoArr = %@", theSQLCOInfoArr);
    if (theSQLCOInfoArr.count > 0){
        
        NSMutableArray *subsidiaryArr = [[[NSMutableArray alloc] init]autorelease];
        for (int i = 0; i < theSQLCOInfoArr.count; i++) {
            NSDictionary *items = [theSQLCOInfoArr objectAtIndex:i];
            NSString *subsidiaryString = [items objectForKey:@"subsidiary"];
            if (![subsidiaryArr containsObject:subsidiaryString]) {
                [subsidiaryArr addObject:subsidiaryString];
            }
        }
        
        NSMutableArray *subTypesArray = [[[NSMutableArray alloc] initWithCapacity:0] autorelease];
        for (int i = 0; i < subsidiaryArr.count; i++) {
            NSString *subsidiaryString = [subsidiaryArr objectAtIndex:i];
            NSMutableArray *subCompanyCharts = [EFBCompanyChartDB getTheCompantChartsByCode4:icao andSubsidiary:subsidiaryString];
            
            NSMutableDictionary *childCompanyChart = [[[NSMutableDictionary alloc]initWithCapacity:0]autorelease];
            NSMutableArray *chartsArray = [[[NSMutableArray alloc] initWithCapacity:0]autorelease];
            for (NSDictionary *itermChart in subCompanyCharts){
                NSMutableDictionary *dic = [[[NSMutableDictionary alloc] initWithCapacity:0]autorelease];
                [dic setValue:@"NO" forKey:@"isChart"];
                [dic setValue:@"0" forKey:@"is_modified"];
                [dic setValue:[itermChart objectForKey:@"name"] forKey:@"name"];
                [dic setValue:[[itermChart objectForKey:@"code4"] uppercaseString] forKey:@"page"];
                [dic setValue:[NSString stringWithFormat:@"%@%@", [itermChart objectForKey:@"file_id"], [itermChart objectForKey:@"file_name"]] forKey:@"file_name"];
                [dic setValue:[itermChart objectForKey:@"uuid"] forKey:@"uuid"];
                [chartsArray addObject:dic];
            }
            [childCompanyChart setObject:subsidiaryString forKey:@"subTypeName"];
            [childCompanyChart setObject:chartsArray forKey:@"chartsArray"];
//            NSLog(@"childCompanyChart = %@", childCompanyChart);
            [subTypesArray addObject:childCompanyChart];
        }
        NSMutableDictionary *coDic = [[[NSMutableDictionary alloc] initWithCapacity:0]autorelease];
        [coDic setObject:@"CO" forKey:@"typeName"];
        [coDic setObject:subTypesArray forKey:@"subTypesArray"];
        if (_typesArray.count > 5) {
            [_typesArray replaceObjectAtIndex:5 withObject:coDic];
        }else{
            [_typesArray addObject:coDic];
        }
    } 
}

- (void)getARDataWithCode4:(NSString *)icao
{
    NSMutableArray *theSQLCOInfoArr = [EFBAviationMapDB getTheAviationChartsByCode4:icao];
//    NSLog(@"theSQLARInfoArr = %@", theSQLCOInfoArr);
    if (theSQLCOInfoArr.count > 0){
        NSMutableDictionary *coDic = [[[NSMutableDictionary alloc] initWithCapacity:0]autorelease];
        [coDic setObject:@"AR" forKey:@"typeName"];
        NSString *titleString = @"RNP AR";
        NSMutableArray *subsidiaryArr = [[[NSMutableArray alloc] initWithObjects:titleString, nil]autorelease];
    
        NSMutableArray *subTypesArray = [[[NSMutableArray alloc] initWithCapacity:0]autorelease];
        for (int i = 0; i < subsidiaryArr.count; i++) {
            NSString *subsidiaryString = [subsidiaryArr objectAtIndex:i];
            NSMutableArray *subCompanyCharts = [EFBAviationMapDB getTheAviationChartsByCode4:icao];
            NSMutableDictionary *childCompanyChart = [[[NSMutableDictionary alloc] initWithCapacity:0]autorelease];
            [childCompanyChart setObject:subsidiaryString forKey:@"subTypeName"];
            NSMutableArray *chartsArray = [[[NSMutableArray alloc] initWithCapacity:0]autorelease];
            for (NSDictionary *itermChart in subCompanyCharts){
                NSMutableDictionary *dic = [[[NSMutableDictionary alloc] initWithCapacity:0]autorelease];
                [dic setValue:@"NO" forKey:@"isChart"];
                [dic setValue:@"0" forKey:@"is_modified"];
                [dic setValue:[itermChart objectForKey:@"name"] forKey:@"name"];
                [dic setValue:icao forKey:@"page"];
                [dic setValue:[NSString stringWithFormat:@"%@%@", [itermChart objectForKey:@"file_id"], [itermChart objectForKey:@"file_name"]] forKey:@"file_name"];
                [chartsArray addObject:dic];
            }
            [childCompanyChart setObject:chartsArray forKey:@"chartsArray"];
//            NSLog(@"childCompanyChart = %@", childCompanyChart);
            [subTypesArray addObject:childCompanyChart];
        }
        [coDic setObject:subTypesArray forKey:@"subTypesArray"];
        if (_typesArray.count > 6) {
            [_typesArray replaceObjectAtIndex:6 withObject:coDic];
        }else{
            [_typesArray addObject:coDic];
        }
    }
}

#pragma mark - 校验单
-(void)showDigestPopover:(id)sender
{
    UIButton *button = (UIButton *)sender;
    if (self.digestPopover.isPopoverVisible) {
        [self.digestPopover dismissPopoverAnimated:NO];
        return;
    }
    if (!self.digestPopover.isPopoverVisible && !_topView.hidden) {
        [self.digestPopover presentPopoverFromRect:button.frame inView:self.topView permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
    }
}

#pragma mark - EFBDigestViewControllerDelegate Method
- (void)didSelectedRowForShowPdfName:(NSString *)pdfName
{
    if (!_chartListViewContoller.view.hidden) {
        [self animateChartListView:NO];
    }
    NSString *pdfPath = [[self getCurrentChartsFolderPath:componentDataName] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.pdf",pdfName]];
    
    [self showPDFWithPath:pdfPath];
    self.topView.titleLabel.text = pdfName;
}

- (NSMutableArray *)getDigestButtonEnable
{
    NSString *checklist = @"校核单";//NSLocalizedString(@"chart-check-list", @"校核单");
    NSString *updatelist = @"修订单";//NSLocalizedString(@"chart-update-list", @"修订单");
    
    NSMutableArray *objectArray = [NSMutableArray array];
    NSString *currentFloderPath = [self getCurrentChartsFolderPath:componentDataName];
    if ([[NSFileManager defaultManager] fileExistsAtPath:[currentFloderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.pdf",JIAOHEDAN]]]) {
        [objectArray addObject:checklist];
    }
    if([[NSFileManager defaultManager] fileExistsAtPath:[currentFloderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.pdf",XIUDINGDAN]]]){
        [objectArray addObject:updatelist];
    }
    if ([objectArray count]>0) {
        self.digestButton.enabled = YES;
    }else{
        self.digestButton.enabled = NO;
    }
    return objectArray;
}

- (void)changeTheVersionChart:(NSNotification *)notice
{
    NSString *curentUUidString = [[NSUserDefaults standardUserDefaults] objectForKey:@"blueUUID"];
    int targetSelectNum = [[notice.object objectForKey:@"selectNum"] intValue];
    if (targetSelectNum != _selectIndex || ![curentUUidString isEqualToString:[notice.object objectForKey:@"blueUUID"]]) {
//        _isBlueTooth = YES;
        if(targetSelectNum == _selectIndex){
            targetSelectNum = (targetSelectNum == 0) ? 1:0;
        }
        [self versionChanged:targetSelectNum];
    }
}


#pragma mark - 登录 注销 时发送的通知
- (void)loginNotification
{
    NSDictionary *userDictionary = [AEIdentityManager defaultManager].currentUser;
    NSString *userName = [userDictionary objectForKey:kUserName];
    NSString *password = [userDictionary objectForKey:kUserEncryptPassword];
    if (!userName || !password)
    {
        [self closeChart];
        [self reloadCharts:nil];
    }
    
    //设备是否已经变化
    NSString *originalValue=[[ChartContext instance] objectForKey:kConextDeviceIsForeign];
    NSString *newValue=[[EFBContext sharedDefaultInstance] objectForkey:kDeviceIsForeign];
    if (originalValue != nil && ![originalValue isEqualToString:@""] && ![originalValue isEqualToString:newValue])
    {
        [self reloadCharts:nil];
    }
}

#pragma mark - gesture method

- (void)gestureForTap:(UITapGestureRecognizer*)recognizer
{
    if (!self.chartListViewContoller.view.hidden) {
        [self animateChartListView:NO];
    }
}

- (void)gestureForSwipe:(UISwipeGestureRecognizer*)recognizer
{
    if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
        [self.favoriteView rightButtonTap];
    }

    if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
        [self.favoriteView leftButtonTap];
    }
}

@end
